import { NextRequest, NextResponse } from 'next/server';
import jwt from 'jsonwebtoken';
import User from '@/models/user';
import { ApiResponse, UserInfo } from '@/types/interface';

export async function GET(request: NextRequest) {
  try {
    // 从cookie中获取token
    const token = request.cookies.get('token')?.value;
    
    if (!token) {
      return NextResponse.json(
        { code: 401, msg: '未登录', data: null },
        { status: 401 }
      );
    }
    
    const secret = process.env.JWT_SECRET;
    if (!secret) {
      return NextResponse.json(
        { code: 500, msg: '服务器配置错误', data: null },
        { status: 500 }
      );
    }
    
    // 验证token
    const decoded = jwt.verify(token, secret) as { id: string; username: string };
    
    // 从数据库中查询用户
    const user: any = await User.findByPk(decoded.id)!;
    
    if (!user) {
      return NextResponse.json(
        { code: 404, msg: '用户不存在', data: null },
        { status: 404 }
      );
    }
    
    // 返回用户信息（不包含密码）
    const userInfo: UserInfo = {
      id: user.id.toString(),
      username: user.username,
      email: user.email,
      roles: ['user'] // 默认角色，可以根据实际需求扩展
    };
    
    const response: ApiResponse<UserInfo> = {
      code: 200,
      msg: '获取用户信息成功',
      data: userInfo
    };
    
    return NextResponse.json(response);
    
  } catch (error) {
    console.error('获取用户信息错误:', error);
    
    if (error instanceof jwt.JsonWebTokenError) {
      return NextResponse.json(
        { code: 401, msg: 'token无效', data: null },
        { status: 401 }
      );
    }
    
    return NextResponse.json(
      { code: 500, msg: '服务器内部错误', data: null },
      { status: 500 }
    );
  }
}